package com.linhui.rpc.serializer.imp;

import com.linhui.rpc.serializer.Serializer;

import java.io.*;

/**
 * @author: 临晖
 * @since: 2024-05-10
 */
public class JDKSerializer implements Serializer {

    @Override
    public <T> byte[] serialize(T object) throws IOException {
        //字节数组输出流
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        //创建序列化器
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
        //将该对象序列化然后写入内存
        objectOutputStream.writeObject(object);
        objectOutputStream.close();

        //输出
        return outputStream.toByteArray();
    }


    @Override
    public <T> T deserialize(byte[] bytes, Class<T> type) throws IOException {
        //将字节数组存入字节数组输入流（存入内存）
        ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
        //创建反序列化器
        ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);

        try {
             return type.cast(objectInputStream.readObject());
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } finally {
            objectInputStream.close();
        }

    }
}
